<template>
  <div class="home">
    <div class="layout">
      <div class="map-wrapper">
        <div id="container"></div>
      </div>
      <task-list></task-list>
      <section class="aside">
        <nav class="nav">
          <span
            v-for="(item,index) of navList"
            :key="index"
            :class="{active:active==index}"
            @click="GoToPart(item.router,index)"
          >{{item.name}}</span>
        </nav>
        <router-view></router-view>
      </section>
    </div>
  </div>
</template>

<script>
import TaskList from "./TaskList";
import hospital from "../assets/image/hospital-unactive.png";
import hospitalActive from "../assets/image/hospital-active.png";
import hospitalbg from "../assets/image/hospitalbg.png";
import event from "../assets/image/map-telephone.png";
import ambulance from "../assets/image/ambulance.png";
// import CONFIG from "../../static/config";
export default {
  name: "Home",
  components: {
    TaskList,
  },
  data() {
    return {
      active: 0,
      navList: [
        {
          name: "医院选择",
          router: "HospitalList",
        },
        {
          name: "院前推送",
          router: "ToldInfo",
        },
        {
          name: "时间轴",
          router: "TaskProgress",
        },
      ],
      ambMarkerList: [],
      map: "",
      timer: "",
      hospitalMarkerList: [],
      hospitalActiveId: "",
    };
  },
  methods: {
    initMap() {
      this.map = new BMapGL.Map("container");
      let point = new BMapGL.Point(116.404, 39.915);
      this.map.centerAndZoom(point, 15);
      this.map.enableScrollWheelZoom(true);
      if (CONFIG.ISSETMAPSTYLE) {
        this.map.setMapStyleV2({
          styleId: "06a1c430d86fc557fc805cef702065a7",
        });
      }
    },
    GetTaskList(centerId) {
      this.$axios({
        data: this.$qs.stringify({
          MessageType: "GetTaskList",
          centerId: centerId,
        }),
        method: "post",
      }).then((res) => {
        console.log("GetTaskList", res);
        if (res.status == 200) {
          let obj = res.data;
          if (obj.status == 200) {
            this.MarkEventOnMap(obj.data);
            this.$store.dispatch("SaveTaskList", obj.data);
          } else {
            this.$message.error(obj.message);
          }
        } else {
          this.$message.error("请求任务列表失败");
        }
      });
    },
    GetAmbulanceGPSList(centerId) {
      this.$axios({
        data: this.$qs.stringify({
          MessageType: "GetAmbulanceGPSList",
          centerId: centerId,
        }),
        method: "post",
      }).then((res) => {
        console.log("GetAmbulanceGPSList", res);
        if (res.status == 200) {
          let obj = res.data;
          if (obj.status == 200) {
            this.MarkAmbOnMap(obj.data);
            this.$store.dispatch("SaveAmbGPSList", obj.data);
          } else {
            this.$message.error(obj.message);
          }
        } else {
          this.$message.error("请求车辆GPS列表失败");
        }
      });
    },
    MarkAmbOnMap(list) {
      list.forEach((item) => {
        if (item.ambX == 0 || item.ambY == 0) {
          this.$message({
            type: "warning",
            message: `${item.ambNum}坐标为空`,
          });
        } else {
          let sign = false;
          if (this.ambMarkerList.length > 0) {
            let ambMarker = this.ambMarkerList.find(
              (q) => q.ambCode == item.ambCode
            );
            if (ambMarker == undefined) {
              sign = true;
            } else {
              ambMarker.mark.setPosition(
                new BMapGL.Point(item.ambX, item.ambY)
              );
              ambMarker.label.setPosition(
                new BMapGL.Point(item.ambX, item.ambY)
              );
              ambMarker.mark.setRotation(item.direction);
            }
          } else {
            sign = true;
          }
          if (sign) {
            // 创建小车图标
            let pt = new BMapGL.Point(item.ambX, item.ambY);
            let myIcon = new BMapGL.Icon(ambulance, new BMapGL.Size(12, 32));
            myIcon.setImageSize(new BMapGL.Size(12, 12));
            let marker = new BMapGL.Marker(pt, {
              icon: myIcon,
            }); // 创建标注
            marker.setRotation(item.direction);
            this.map.addOverlay(marker); // 将标注添加到地图中

            let opts = {
              position: pt, // 指定文本标注所在的地理位置
              offset: new BMapGL.Size(-27, 19), //设置文本偏移量
            };
            let label = new BMapGL.Label(item.ambRealSign, opts); // 创建文本标注对象
            label.setStyle({
              fontSize: "12px",
              fontFamily: "微软雅黑",
            });
            this.map.addOverlay(label);

            this.ambMarkerList.push({
              ambCode: item.ambCode,
              mark: marker,
              label: label,
            });
          }
        }
      });
    },
    MarkEventOnMap(list) {
      list.forEach((item) => {
        if (item.eventX == 0 || item.eventY == 0) {
          this.$message({
            type: "warning",
            message: `${item.address}坐标为空`,
          });
        } else {
          // 创建小车图标
          let pt = new BMapGL.Point(item.eventX, item.eventY);
          let myIcon = new BMapGL.Icon(event, new BMapGL.Size(30, 30));
          let marker = new BMapGL.Marker(pt, {
            icon: myIcon,
          }); // 创建标注
          this.map.addOverlay(marker); // 将标注添加到地图中
        }
      });
    },
    MoveToPosition(position) {
      this.map.panTo(new BMapGL.Point(position.X, position.Y));
    },
    MarkHospitalOnMap() {
      let hospitals = this.$store.state.hospitalList;
      if (hospitals.length == 0) {
        return;
      }
      hospitals.forEach((item) => {
        if (item.longitude == 0 || item.latitude == 0) {
          this.$message({
            type: "warning",
            message: `${item.name}坐标为空`,
          });
        } else {
          // 创建小车图标
          let pt = new BMapGL.Point(item.longitude, item.latitude);
          let myIcon = new BMapGL.Icon(hospital, new BMapGL.Size(30, 30));
          let marker = new BMapGL.Marker(pt, {
            icon: myIcon,
          }); // 创建标注
          this.map.addOverlay(marker); // 将标注添加到地图中
          this.hospitalMarkerList.push({ marker: marker, id: item.id });
          let opts = {
            position: pt, // 指定文本标注所在的地理位置
            offset: new BMapGL.Size(10, -20), //设置文本偏移量
          };
          let label = new BMapGL.Label(item.name, opts); // 创建文本标注对象
          label.setStyle({
            color: "#fff",
            fontSize: "12px",
            height: "20px",
            lineHeight: "20px",
            fontFamily: "微软雅黑",
            backgroundImage: `url(${hospitalbg})`,
            backgroundColor: "rgba(0,0,0,0)",
            backgroundSize: "100% 100%",
            padding: "0 10px",
            border: "none",
          });
          this.map.addOverlay(label);
        }
      });
    },
    SortHospitalNearPosition(position) {
      let hospitals = this.$store.state.hospitalList;
      if (hospitals.length == 0) {
        return;
      }
      let points = hospitals
        .filter((q) => q.latitude != 0 && q.longitude != 0)
        .map((q) => [q.latitude, q.longitude]);
      this.$jsonp(
        `https://api.map.baidu.com/routematrix/v2/driving?output=json&tactics=11&coord_type=bd09ll&origins=${
          position.Y
        },${position.X}&destinations=${points.join("|")}&ak=${CONFIG.MAPKEY}`
      )
        .then((res) => {
          console.log("SortHospitalNearPosition", res);
          if (res.status == 0) {
            this.$store.dispatch("SortHospital", res.result);
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    GoToPart(router, index) {
      this.active = index;
      this.$router.push({ name: router });
      if (this.hospitalActiveId != "") {
        this.RepalceHospitalMarker(this.hospitalActiveId, hospital);
        this.hospitalActiveId = "";
        this.$store.commit("SaveCheckedHospital", "");
      }
    },
    RepalceHospitalMarker(id, img) {
      let item = this.hospitalMarkerList.find((q) => q.id == id);
      item.marker.setIcon(new BMapGL.Icon(img, new BMapGL.Size(30, 30)));
    },
  },
  mounted() {
    this.initMap();
    this.MarkHospitalOnMap();
    let centerId = this.$store.state.centerId;
    if (centerId == "") {
      this.$router.push({ name: "Index" });
    } else {
      this.GetTaskList(centerId);
      this.GetAmbulanceGPSList(centerId);
      this.timer = setInterval(() => {
        this.GetAmbulanceGPSList(centerId);
      }, 10000);
    }
  },
  watch: {
    "$store.state.clickedPosition": {
      handler(val) {
        if (val.X == 0 || val.Y == 0) {
          this.$message({
            type: "warning",
            message: `坐标为空，不能计算预估时间和预估距离！`,
          });
        } else {
          this.MoveToPosition(val);
          this.SortHospitalNearPosition(val);
        }
      },
      deep: true,
    },
    "$store.state.checkedHospital": {
      handler(val) {
        if (val == "") {
          return;
        }
        if (val.X == 0 || val.Y == 0) {
          this.$message({
            type: "warning",
            message: `医院坐标为空，无法移动到医院！`,
          });
        } else {
          this.RepalceHospitalMarker(val.id, hospitalActive);
          if (this.hospitalActiveId == "") {
          } else {
            this.RepalceHospitalMarker(this.hospitalActiveId, hospital);
          }
          this.hospitalActiveId = val.id;
          this.MoveToPosition(val);
        }
      },
      deep: true,
    },
  },
  destroyed() {
    clearInterval(this.timer);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.home {
  height: 90%;
}
.layout {
  height: 100%;
  position: relative;
}
.map-wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
#container {
  height: 100%;
  width: 100%;
}
.aside {
  position: absolute;
  right: 50px;
  top: 5%;
  height: 90%;
  width: 400px;
  display: flex;
  flex-direction: column;
  z-index: 99;
}
.nav {
  display: flex;
  color: #fff;
  height: 8%;
  justify-content: center;
  align-items: center;
}
.nav > span {
  background: rgba(0, 121, 161, 0.1);
  border: 1px solid rgba(0, 185, 247, 0.5);
  width: 30%;
  text-align: center;
  padding: 5px 0;
  cursor: pointer;
  font-size: 20px;
}
.active {
  background: rgba(23, 126, 229, 0.5) !important;
}
</style>